package info.marlan.sipgate;

import info.marlan.sipgate.model.HistoryEntry;
import info.marlan.sipgate.model.SipgateAccount;
import info.marlan.util.ConvertUtil;
import info.marlan.util.DBHelper;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;



public class WidgetProvider extends AppWidgetProvider {
	
	public static final String LOGTAG = "sipgate";
	public final static int MAXLENGTH = 14;
	@Override
	 public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		 //Log.v(LOGTAG, "WidgetProvider#onUpdate");
	     Intent i = new Intent(context, SipGateService.class);
	      //  i.putExtra(SipGateService.ON_UPDATE, true);
	     context.startService(i);
	    }

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		//Log.v(LOGTAG, "WidgetProvider#onDeleted");
		super.onDeleted(context, appWidgetIds);
        final int N = appWidgetIds.length;
        DBHelper dbHelper  = new DBHelper(context);
        try{
	        for (int i=0; i<N; i++) {
	        	dbHelper.deleteAccount(appWidgetIds[i]);
	        }
        }catch(Exception e){
        	Log.e(LOGTAG, e.getMessage());
        }finally{
        	if(dbHelper!=null){
        	dbHelper.cleanup();
        	dbHelper=null;
        	}
        }
	}

	@Override
	public void onDisabled(Context context) {
		//Log.v(LOGTAG, "WidgetProvider#onDisabled");

		super.onDisabled(context);
	}

	@Override
	public void onEnabled(Context context) {
		//Log.v(LOGTAG, "WidgetProvider#onEnabled");
		
		super.onEnabled(context);
	}


	@Override
	public void onReceive(Context context, Intent intent) {
	//	Log.v(LOGTAG, "WidgetProvider#onReceive");
	    final String action = intent.getAction();
	    if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
	    	 Bundle extras = intent.getExtras();
	    	 if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
	    		 final int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
	    		 if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
	    			 this.onDeleted(context, new int[] { appWidgetId });
	    		 }
	    	 }
	    } else {
	        super.onReceive(context, intent);
	    }
	} 

    
    static void updateAppWidgetView(Context context, AppWidgetManager appWidgetManager,
            HistoryEntry entry, SipgateAccount account){
       
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider);
        
        String remoteNumber = entry.getPhoneBookName();
        String localNumber = ConvertUtil.getBaseNumber(entry.getLocalUri()) ;

        views.setViewVisibility(R.id.no_result, View.GONE);
        views.setViewVisibility(R.id.result, View.VISIBLE);
        views.setViewVisibility(R.id.result1, View.VISIBLE);
        views.setTextViewText(R.id.local,localNumber!=null && localNumber.length() > WidgetProvider.MAXLENGTH ? localNumber.substring(0, WidgetProvider.MAXLENGTH)+"...": localNumber );
        views.setImageViewResource(R.id.status, ConvertUtil.getStatusIcon(entry.getStatus()));
        
        Intent touchIntent = new Intent(context,LogListActivity.class);
        touchIntent.putExtra(LogListActivity.WIDGETID,entry.getWidgetId());
    
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, touchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.MainLayout,  pendingIntent);
        
        views.setTextViewText(R.id.balance,ConvertUtil.formatBalance(account.getBalance()));	
        
        views.setTextViewText(R.id.tos, entry.gettOS() );
        views.setTextViewText(R.id.remote,remoteNumber!=null && remoteNumber.length() > WidgetProvider.MAXLENGTH ? remoteNumber.substring(0, WidgetProvider.MAXLENGTH)+"...": remoteNumber );
        String d = android.text.format.DateFormat.getDateFormat(context).format(entry.getTimestamp()) +" "+android.text.format.DateFormat.getTimeFormat(context).format(entry.getTimestamp())+"h";
        //ConvertUtil.getDisplayTimestamp(entry.getTimestamp())
        views.setTextViewText(R.id.date, d);

        appWidgetManager.updateAppWidget(entry.getWidgetId(), views);
    }

}
